<template>
	<el-dialog title="批量新增AI模型" v-model="visible" :close-on-click-modal="false" draggable width="600px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" v-loading="loading">
			<el-form-item prop="apiKey" class="relative">
				<el-input
					v-model="form.apiKey"
					placeholder="请输入API Key（格式：sk-开头，长度51位）"
					type="textarea"
					show-word-limit
					maxlength="51"
					rows="2"
				/>
				<div class="absolute -bottom-5 right-2 text-xs z-10 bg-white/90 px-2 py-1 rounded">
					<a href="https://cloud.siliconflow.cn/i/YKcJJTYP" target="_blank" class="text-blue-500 hover:text-blue-700 no-underline text-xs">获取【硅基流动】 免费 ApiKey</a>
				</div>
			</el-form-item>

			<el-form-item>
				<el-card class="mt-4">
					<template #header>
						<span>将要创建的模型（共{{ previewModels.length }}个）</span>
					</template>
					<div class="flex flex-wrap gap-2">
						<el-tag v-for="model in previewModels" :key="model.type" class="mb-2 mr-2" type="primary">
							{{ model.typeLabel }}: {{ model.modelName }}
						</el-tag>
					</div>
				</el-card>
			</el-form-item>
		</el-form>
		
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">批量创建</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="BatchAiModelDialog">
import { useMessage } from '/@/hooks/message';
import { addObj, details } from '/@/api/knowledge/aiModel';
import { ref, reactive, nextTick } from 'vue';

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);

// 提交表单数据
const form = reactive({
	apiKey: ''
});

// 定义校验规则
const dataRules = ref({
	apiKey: [
		{ required: true, message: '请输入API Key', trigger: 'blur' },
		{ 
			validator: (rule: any, value: any, callback: any) => {
				if (!value) {
					callback(new Error('请输入API Key'));
					return;
				}
				if (!value.startsWith('sk-')) {
					callback(new Error('API Key必须以sk-开头'));
					return;
				}
				if (value.length !== 51) {
					callback(new Error('API Key长度必须为51位'));
					return;
				}
				callback();
			}, 
			trigger: 'blur' 
		}
	]
});

// 预览要创建的模型
const previewModels = ref([
	{ 
		type: 'Chat', 
		typeLabel: '聊天', 
		modelName: 'moonshotai/Kimi-K2-Instruct',
		name: 'kimi-k2',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Chat', 
		typeLabel: '聊天', 
		modelName: 'deepseek-ai/DeepSeek-V3.1',
		name: 'deepseek-chat',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Embedding', 
		typeLabel: '向量', 
		modelName: 'Qwen/Qwen3-Embedding-8B',
		name: 'qwen-embedding',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Reranker', 
		typeLabel: '排序', 
		modelName: 'Qwen/Qwen3-Reranker-8B',
		name: 'qwen-reranker',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Image', 
		typeLabel: '图片', 
		modelName: 'Kwai-Kolors/Kolors',
		name: 'kolors-image',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Reason', 
		typeLabel: '推理', 
		modelName: 'MiniMaxAI/MiniMax-M1-80k',
		name: 'minimax-reason',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Vision', 
		typeLabel: '视觉', 
		modelName: 'Qwen/Qwen2.5-VL-72B-Instruct',
		name: 'qwen-vision',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Video', 
		typeLabel: '视频', 
		modelName: 'Wan-AI/Wan2.2-T2V-A14B',
		name: 'wan-video',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	},
	{ 
		type: 'Voice', 
		typeLabel: '音频', 
		modelName: 'RVC-Boss/GPT-SoVITS',
		name: 'gpt-sovits',
		provider: 'Siliconflow',
		baseUrl: 'https://api.siliconflow.cn/v1'
	}
]);

// 检查模型名称是否存在
const checkModelExists = async (name: string): Promise<boolean> => {
	try {
		const response = await details({ name });
		return response.data !== null && response.data.length > 0;
	} catch (error) {
		return false;
	}
};

// 打开弹窗
const openDialog = () => {
	visible.value = true;
	
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
		form.apiKey = '';
	});
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		
		let successCount = 0;
		let failedCount = 0;
		let skipCount = 0;
		const errors: string[] = [];
		const skipped: string[] = [];

		// 使用单个API Key为每个模型创建
		for (const model of previewModels.value) {
			try {
				// 先检查模型名称是否存在
				const exists = await checkModelExists(model.name);
				if (exists) {
					skipCount++;
					skipped.push(`${model.typeLabel}模型(${model.name})已存在，跳过创建`);
					continue;
				}

				const modelData = {
					modelType: model.type,
					modelName: model.modelName,
					name: model.name,
					provider: model.provider,
					baseUrl: model.baseUrl,
					apiKey: form.apiKey.trim(),
					defaultModel: '1', // 非默认模型
					extData: '{}',
					// 为Chat类型设置默认参数
					...(model.type === 'Chat' && {
						responseLimit: 2048,
						temperature: 0.4,
						topP: 0.7
					}),
					// 为Image类型设置默认参数
					...(model.type === 'Image' && {
						imageSize: '1024x1024',
						imageQuality: 'standard',
						imageStyle: 'natural'
					})
				};

				await addObj(modelData);
				successCount++;
			} catch (err: any) {
				failedCount++;
				errors.push(`${model.typeLabel}模型(${model.modelName})创建失败: ${err.msg || '未知错误'}`);
			}
		}

		// 显示结果
		const resultMessages = [];
		if (successCount > 0) {
			resultMessages.push(`成功创建${successCount}个AI模型`);
		}
		if (skipCount > 0) {
			resultMessages.push(`跳过${skipCount}个已存在的模型`);
		}
		if (failedCount > 0) {
			resultMessages.push(`失败${failedCount}个`);
		}

		if (resultMessages.length > 0) {
			useMessage().success(resultMessages.join('，'));
		}
		
		// 显示跳过的模型信息
		if (skipped.length > 0 && skipped.length <= 3) {
			skipped.forEach(msg => useMessage().warning(msg));
		} else if (skipped.length > 3) {
			useMessage().warning(`共跳过${skipCount}个已存在的模型`);
		}
		
		// 显示错误信息
		if (errors.length > 0 && errors.length <= 3) {
			errors.forEach(error => useMessage().error(error));
		} else if (errors.length > 3) {
			useMessage().error(`批量创建完成，有${failedCount}个模型创建失败`);
		}

		if (successCount > 0 || skipCount > 0) {
			visible.value = false;
			emit('refresh');
		}
	} catch (err: any) {
		useMessage().error(err.msg || '批量创建失败');
	} finally {
		loading.value = false;
	}
};

// 暴露变量
defineExpose({
	openDialog,
});
</script> 